package com.wulian.user.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wulian.common.constants.CommonConstants;
import com.wulian.common.controller.BaseController;
import com.wulian.common.dto.UserInfo;
import com.wulian.common.vo.MenuVO;
import com.wulian.common.vo.ResultMoudel;
import com.wulian.common.vo.UserVO;
import com.wulian.user.dto.DeptTree;
import com.wulian.user.entity.SysDept;
import com.wulian.user.entity.SysTree;
import com.wulian.user.mapper.SysUserMapper;
import com.wulian.user.service.SysDeptService;
import com.wulian.user.service.SysMenuService;
import com.wulian.user.service.SysTreeService;
import com.wulian.user.service.SysUserService;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * <p>
 * 机构管理 前端控制器
 * </p>
 *
 * @author Administrator
 * @since 2018-01-20
 */
@RestController
@RequestMapping("/dept")
public class DeptController extends BaseController<UserInfo> {
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysTreeService sysTreeService;

    /**
     * 通过ID查询
     *
     * @param id ID
     * @return SysDept
     */
    @GetMapping("/{id}")
    public SysDept get(@PathVariable Integer id) {
        return sysDeptService.selectSysDeptById(id);
    }


    /**
     * 返回树形菜单集合
     *
     * @return 树形菜单
     */
    @GetMapping(value = "/tree")
    public List<DeptTree> getTree() {
    	UserInfo user = getCurrentUser();
        return sysDeptService.selectListTree(user.getSysUser().getDeptId());
    }

    /**
     * 组织管理 - 返回所属客户及root节点的树形组织结构
     *
     * @return 树形菜单
     */
    @GetMapping(value = "/clienttree")
    public List<DeptTree> getClientTree(@RequestBody Map<String,Object> map) {
        UserInfo user = getCurrentUser();
        return sysDeptService.selectListTree_client(map, user.getSysUser().getDeptId());
    }

    /**
     * 添加
     *
     * @param sysDept 实体
     * @return success/false
     */
    @PostMapping
    public ResultMoudel add(@RequestBody SysDept  sysDept) {
    	UserInfo user = getCurrentUser();
    	//所勾选的菜单
    	String menuIds = sysDept.getMenuIds();
    	Integer[] menuIdArr = null;
    	if(StringUtils.isNotBlank(menuIds)){
    		String[] menuIdArray = menuIds.split(",");
    		//将String数组转成Integer数组
    		menuIdArr = Arrays.stream(menuIdArray).map(Integer::valueOf).toArray(Integer[]::new);
    	}else{
    		Map<String, Object> paramMap = new HashMap<String, Object>();
    		paramMap.put("username", user.getSysUser().getUsername());
    		paramMap.put("status", CommonConstants.STATUS_NORMAL);
    		UserVO selectUser = sysUserMapper.selectUserVoByUsername(paramMap);
        	List<String> roleCodeList = selectUser.getRoleList().stream().map(sr -> sr.getRoleCode()).collect(Collectors.toList());
            // 获取符合条件得菜单
            List<MenuVO> all = new ArrayList<>();
            roleCodeList.forEach(roleName -> all.addAll(sysMenuService.findMenuByRoleName(roleName)));
            //菜单过滤并转为List<Integer>
            List<Integer> menuIdList = all.stream().filter(menu -> CommonConstants.MENU.equals(menu.getType()))
            		.map(mtl -> Integer.valueOf(mtl.getMenuId())).collect(Collectors.toList());
            menuIdArr = menuIdList.stream().map(Integer :: valueOf).toArray(Integer[]::new);
    	}

    	// 在新增部门时强制将setDeptCode进行赋值，防止DeptCode重复导致的一系列BUG
        sysDept.setDeptCode(String.valueOf(new Date().getTime()));
        if(sysDeptService.insertDept(sysDept,menuIdArr,user.getSysUser().getCompanyId())){
            // 前端使用要求追加deptCode的返回值
            return new ResultMoudel().success(sysDept);
        }
        return new ResultMoudel().success("操作失败");
    }


    /**
     * 删除
     *
     * @param id ID
     * @return success/false
     */
    @DeleteMapping("/{id}")
    public ResultMoudel delete(@PathVariable Integer id) {
        if(sysDeptService.deleteDeptById(id)){
            return new ResultMoudel().success("操作成功");
        }
        return new ResultMoudel().success("操作失败");
    }

    /**
     * 编辑
     *
     * @param sysDept 实体
     * @return success/false
     */
    @PutMapping
    public ResultMoudel edit(@RequestBody SysDept sysDept) {
        sysDept.setUpdateTime(new Date());
        if(sysDeptService.updateDeptById(sysDept)){
            return new ResultMoudel().success("操作成功");
        }
        return new ResultMoudel().success("操作失败");
    }

    /**
     * 当前登陆人员所在管理机构
     *
     * @param
     * @return SysDept
     */
    @ApiOperation(value = "getDeptTheCurrentLangPeople", notes = "当前登陆人员所在管理机构")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "当前登陆人员所在管理机构") })
    @GetMapping("getDeptTheCurrentLangPeople")
    public SysDept getDeptTheCurrentLangPeople() {
    	UserInfo currentUser = getCurrentUser();
        return sysDeptService.selectSysDeptById(userService.selectUserVoById(currentUser.getSysUser().getUserId()).getDeptId());
    }

    /**
     * 校验机构code唯一
     *
     * @return boolean
     */
    @PostMapping("/checkCodeUnique/{deptCode}")
    @ApiOperation(value = "checkCodeUnique", notes = "校验机构code唯一")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "渠道编码可用") })
    public Boolean checkCodeUnique(@PathVariable String deptCode) {
        return sysDeptService.checkCodeUnique(deptCode);
    }

    /**
     * 通过机构编码查询
     *
     * @param deptCode
     * @return SysDept
     */
    @GetMapping("getSysDeptByDeptCode/{deptCode}")
    public SysDept getSysDeptByDeptCode(@PathVariable("deptCode") String deptCode) {
        return sysDeptService.getSysDeptByDeptCode(deptCode);
    }

    /**
     * 查询所有机构
     * @return
     */
    @PostMapping("/selectSysDeptList")
    public List<SysDept> selectSysDeptList() {
        return sysDeptService.selectSysDeptList();
    }

    /**
     * 编辑
     *
     * @param sysDept 实体
     * @return success/false
     */
    @PostMapping("/updateObj")
    public Boolean updateObj(@RequestBody SysDept sysDept) {
        return sysDeptService.updateObj(sysDept);
    }
    
    /**
     * 
    * @Title: selectSysDeptListByUserId
    * @Description:(查询当前登录人下的所有部门)
    * @param @return    参数
    * @return ResultMoudel    返回类型
    * @author mzh
    * @date 2020年4月13日
    * @version V1.0
    * @throws
     */
    @PostMapping("/selectSysDeptListByUserId")
    public ResultMoudel selectSysDeptListByUserId(){
    	UserInfo currentUser = getCurrentUser();
    	Integer deptId = currentUser.getSysUser().getDeptId();
    	//当前用户所在部门及其下属部门集合
    	SysTree sysTree = new SysTree();
    	sysTree.setTypeId(2);
    	sysTree.setChriledId(Long.valueOf(deptId));
    	//获取当前用户所属部门下所有的部门信息
    	List<SysTree> selectListChannel = sysTreeService.selectListChannel(sysTree);
    	//转换为List<String>
    	List<String> deptIdList = selectListChannel.stream()
        		.map(st -> String.valueOf(st.getChriledId())).collect(Collectors.toList());
    	//所有的部门数据
    	List<SysDept> selectSysDeptList = sysDeptService.selectSysDeptList();
    	//过滤符合的部门
    	selectSysDeptList = selectSysDeptList.stream().filter(srdl -> deptIdList.contains(String.valueOf(srdl.getDeptId())))
    			.collect(Collectors.toList());
    	return new ResultMoudel("success",selectSysDeptList);
    }
    /**
     * 功能描述: <br>
     * 〈根据机构id查询下辖的机构〉
     * @Param:
     * @Return:
     * @Author: caifulin
     * @Date: 2020/5/13
     */
    @PostMapping("/selectSysDeptListByDeptId")
    public ResultMoudel selectSysDeptListByDeptId(@RequestBody SysDept sysDept){

        Integer deptId = sysDept.getDeptId();
        //当前用户所在部门及其下属部门集合
        SysTree sysTree = new SysTree();
        sysTree.setTypeId(2);
        sysTree.setChriledId(Long.valueOf(deptId));
        //获取当前用户所属部门下所有的部门信息
        List<SysTree> selectListChannel = sysTreeService.selectListChannel(sysTree);
        //转换为List<String>
        List<String> deptIdList = selectListChannel.stream()
                .map(st -> String.valueOf(st.getChriledId())).collect(Collectors.toList());
        //所有的部门数据
        List<SysDept> selectSysDeptList = sysDeptService.selectSysDeptList();
        //过滤符合的部门
        selectSysDeptList = selectSysDeptList.stream().filter(srdl -> deptIdList.contains(String.valueOf(srdl.getDeptId())))
                .collect(Collectors.toList());
        return new ResultMoudel("success",selectSysDeptList);
    }
    /**
     *
     * @Title: selectSysUserProjectTree
     * @Description:(查询当前登录人所在部门及其下属部门的项目树)
     * @param @return    参数
     * @return ResultMoudel    返回类型
     * @author mzh
     * @date 2020年5月9日
     * @version V1.0
     * @throws
     */
    @PostMapping("/selectSysUserProjectTree")
    public ResultMoudel selectSysUserProjectTree(Integer deviceId){
        UserInfo currentUser = getCurrentUser();
        List selectSysUserProjectTree = sysDeptService.selectSysUserProjectTree(deviceId, currentUser.getSysUser().getUserId());
        return new ResultMoudel(ResultMoudel.SUCCESS_FLAG,selectSysUserProjectTree);
    }
}
